﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using ProtoBuf;

namespace WorldOfSuperpowers_COMMON
{
    public class ProtoTranslater
    {
        #region 单例
        private static ProtoTranslater instance;

        private ProtoTranslater()
        {

        }

        public static ProtoTranslater GetInstance()
        {
            if (instance == null)
            {
                instance = new ProtoTranslater();
            }
            return instance;
        }
        #endregion

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="infos">二进制数据</param>
        /// <returns></returns>
        public T GetTypeFromBytes<T>(byte[] infos)
        {
            using (MemoryStream ms = new MemoryStream())
                {
                    //将消息写入流中
                    ms.Write(infos, 0, infos.Length);
                    //将流的位置归0
                    ms.Position = 0;
                    //使用工具反序列化对象
                    T result = Serializer.Deserialize<T>(ms);
                    return result;
                }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="infos">二进制数据</param>
        /// <returns></returns>
        public T GetTypeFromBytes<T>(object infos)
        {
            byte[] bytesInfo = (byte[]) infos;
            return GetTypeFromBytes<T>(bytesInfo);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="model">类对象</param>
        /// <returns></returns>
        public byte[] GetBytesFromType<T>(T model)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //使用ProtoBuf工具的序列化方法
                Serializer.Serialize<T>(ms, model);
                //定义二级制数组，保存序列化后的结果
                byte[] result = new byte[ms.Length];
                //将流的位置设为0，起始点
                ms.Position = 0;
                //将流中的内容读取到二进制数组中
                ms.Read(result, 0, result.Length);
                return result;
            }

        }
    }
}
